<template>
  <a-modal
    v-model:open="visible"
    title="添加管理员"
    centered
    ok-text="确认"
    cancel-text="取消"
    :force-render="true"
    :width="416"
    :maskClosable="false"
    :okButtonProps="{ loading: loading }"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="选择角色"
          name="roleIds"
          :rules="[{ required: true, message: '请选择角色!' }]"
        >
          <a-select
            v-model:value="formState.roleIds"
            mode="multiple"
            allow-clear
            style="width:200px"
            placeholder="请选择角色"
            :options="roles"
          />
        </a-form-item>

        <a-form-item
          label="管理员姓名"
          name="name"
          :rules="[{ required: true, message: '请输入管理员姓名!' }]"
        >
          <a-input
            v-model:value="formState.name"
            allow-clear
            style="width:200px"
            placeholder="请输入管理员姓名"
          />
        </a-form-item>

        <a-form-item
          label="邮箱"
          name="email"
          :rules="[{ required: true, message: '请输入管理员邮箱!' }]"
        >
          <a-input
            v-model:value="formState.email"
            allow-clear
            style="width:200px"
            placeholder="请输入管理员邮箱"
          />
        </a-form-item>

        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入登录密码!' }]"
        >
          <a-input-password
            v-model:value="formState.password"
            allow-clear
            autocomplete="new-password"
            style="width:200px"
            placeholder="请输入登录密码"
          />
        </a-form-item>

        <a-form-item label="禁止登录" name="is_ban_login">
          <a-switch v-model:checked="checked" @change="onSwitchChange" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import { adminUser } from "@/api";

interface Props {
  roleId: number;
  refresh: boolean;
  open: boolean;
  onCancel: () => void;
}

const props = defineProps<Props>();
const emit = defineEmits(["update:open", "cancel"]);

const visible = ref(props.open);
const formRef = ref();
const init = ref(true);
const loading = ref(false);
const roles = ref<{ label: string; value: number }[]>([]);
const checked = ref(false);

const formState = reactive({
  roleIds: [] as number[],
  name: "",
  email: "",
  password: "",
  is_ban_login: 0,
});

// 表单校验规则
const rules = {
  roleIds: [{ required: true, message: "请选择角色!" }],
  name: [{ required: true, message: "请输入管理员姓名!" }],
  email: [{ required: true, message: "请输入管理员邮箱!" }],
  password: [{ required: true, message: "请输入登录密码!" }],
};

watch(
  () => props.open,
  (val) => {
    visible.value = val;
    if (val) {
      init.value = true;
      getParams();
    }
  }
);

watch(
  () => [props.roleId, props.open],
  () => {
    const roleIds: number[] = [];
    if (props.roleId) {
      roleIds.push(props.roleId);
    }
    formState.roleIds = roleIds;
    formState.email = "";
    formState.name = "";
    formState.password = "";
    formState.is_ban_login = 0;
  },
  { immediate: true }
);

const getParams = () => {
  adminUser.createAdminUser().then((res: any) => {
    const arr: { label: string; value: number }[] = [];
    let data = res.data.roles || [];
    for (let i = 0; i < data.length; i++) {
      arr.push({
        label: data[i].name,
        value: data[i].id,
      });
    }
    roles.value = arr;
    init.value = false;
  });
};

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    loading.value = true;
    await adminUser.storeAdminUser(
      formState.name,
      formState.email,
      formState.password,
      formState.is_ban_login,
      formState.roleIds
    );
    message.success("保存成功！");
    handleCancel();
  } catch (e) {
    console.error("提交失败", e);
  } finally {
    loading.value = false;
  }
};

// 关闭
const handleCancel = () => {
  emit("cancel");
  emit("update:open", false);
};

const onSwitchChange = (val: boolean) => {
  formState.is_ban_login = val ? 1 : 0;
};
</script>
